package com.pro.addresslist.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.pro.addresslist.R;
import com.pro.addresslist.dal.bll.ContactInfoBLL;
import com.pro.addresslist.dal.bll.RelationshipBLL;
import com.pro.addresslist.dal.model.ContactInfoBySqlite;
import com.pro.addresslist.dal.model.Relationship;
import com.pro.addresslist.sqllite.ContactInfoServise;
import com.pro.addresslist.tools.constantUtil;
import com.pro.addresslist.ui.adapter.CommonAdapter;
import com.pro.addresslist.ui.adapter.ViewHolder;
import com.pro.addresslist.ui.common.BaseActivity;

public class externalActivity extends BaseActivity {
	List<Relationship> list = new ArrayList<Relationship>();

	private Button btnSave;
	private Button btnNew;
	private Button btnqueding;
	private ListView gr;
	private CommonAdapter<Relationship> test;
	private android.widget.CheckBox CheckBox;
	private Boolean editMode = true;

	private String type;
	private String id;
	private String relation = "";
	private String parentID;
	private int postion;
	private Boolean islast;
	private String Updata_relation;
	HashMap<Integer, Boolean> state = new HashMap<Integer, Boolean>();  
	//选中关系
	List<String> SelectShipList = new ArrayList<String>();

	private Handler myHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 0x1222) {
				Intent intents = new Intent();
				Bundle bundle = new Bundle();
				bundle.putString("relation", relation);
				intents.putExtras(bundle);
				if (type.equals("dy")) {
					setResult(0, intents);
					finish();
				}
				if (type.equals("gk")) {
					setResult(1, intents);
					finish();
				}
			}
			if(msg.what==constantUtil.Num_SelectContactBydy){
				List<ContactInfoBySqlite> list=(List<ContactInfoBySqlite>) msg.obj;
				if(list.size()!=0){
					ArrayList<String> telNum=new ArrayList<String>();
					for(ContactInfoBySqlite con:list){
						String temTelNum=con.get_MobileEn().split(",")[0];
						telNum.add(temTelNum);
					}
					disMissDialog();
					Intent intents = new Intent(externalActivity.this,SendMsgActivity.class);
					intents.putStringArrayListExtra("telNum", telNum);
					startActivity(intents);
					finish();
				}
				else {
					disMissDialog();
					Toast.makeText(mContext, "该分组没有联系人！", Toast.LENGTH_SHORT).show();
				}
			}
			if(msg.what==constantUtil.Num_SelectContactBygk){
				List<ContactInfoBySqlite> list=(List<ContactInfoBySqlite>) msg.obj;
				if(list.size()!=0){
					ArrayList<String> telNum=new ArrayList<String>();
					for(ContactInfoBySqlite con:list){
						String temTelNum=con.get_MobileEn().split(",")[0];
						telNum.add(temTelNum);
					}
					disMissDialog();
					Intent intents = new Intent(externalActivity.this,SendMsgActivity.class);
					intents.putStringArrayListExtra("telNum", telNum);
					startActivity(intents);
					finish();
				}
				else {
					disMissDialog();
					Toast.makeText(mContext, "该分组没有联系人！", Toast.LENGTH_SHORT).show();
				}
			}
		};
	};

	public class ReceiveBroadCast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals("SelectShip")) {
				// 得到广播中得到的数据，并显示出来
				List<Relationship> listRela = (List<Relationship>) intent
						.getSerializableExtra("parameter");
				if (listRela.size() != 0) {
					islast = false;
					list.clear();
					for (Relationship rela : listRela) {
						if (type.equals("dy")) {
							ContactInfoBLL.SelectContactNumBydy(mContext,
									rela.get_Name());
						}
						if (type.equals("gk")) {
							ContactInfoBLL.SelectContactNumBygk(mContext,
									rela.get_Name());
						}
						list.add(rela);
					}
					test.notifyDataSetChanged();
				} else {
					islast = true;
					if (id != null) {
						String[] ss = relation.split("-");
						String gkdy = ss[ss.length - 1];
						if (type.equals("dy")) {
							Intent intentdy = new Intent(mContext,
									ContactsActivity.class);
							intentdy.putExtra("action", "dy");
							intentdy.putExtra("gkdy", gkdy);
							startActivity(intentdy);
						}
						if (type.equals("gk")) {
							Intent intentgk = new Intent(mContext,
									ContactsActivity.class);
							intentgk.putExtra("action", "gk");
							intentgk.putExtra("gkdy", gkdy);
							startActivity(intentgk);
						}
					} else {
						Message msg = new Message();
						msg.what = 0x1222;
						// 发送消息
						myHandler.sendMessage(msg);
					}
				}
			}
			if (action.equals("lbs_SelectContactNumBydy")) {
				// 得到广播中得到的数据，并显示出来
				String num = (String) intent.getSerializableExtra("parameter");
				String dy = (String) intent.getSerializableExtra("dy");
				for (int i = 0; i < list.size(); i++) {
					if (dy.equals(list.get(i).get_Name())) {
						list.get(i).set_Depict(num);
					}
				}
				test.notifyDataSetChanged();
			}
			if (action.equals("lbs_SelectContactNumBygk")) {
				// 得到广播中得到的数据，并显示出来
				String num = (String) intent.getSerializableExtra("parameter");
				String gk = (String) intent.getSerializableExtra("gk");
				for (int i = 0; i < list.size(); i++) {
					if (gk.equals(list.get(i).get_Name())) {
						list.get(i).set_Depict(num);
					}
				}
			}
			if (action.equals("AddShip")) {
				String reslut = (String) intent.getStringExtra("result");
				if (reslut.equals("succeed")) {
					RelationshipBLL.SelectShip(mContext, parentID);
				} else {
					Toast.makeText(externalActivity.this, "关系添加失败！",
							Toast.LENGTH_SHORT).show();
				}
			}
			if (action.equals("DeleteShip")) {
				String reslut = (String) intent.getStringExtra("result");
				if (reslut.equals("succeed")) {
					list.remove(postion);
					Toast.makeText(externalActivity.this, "关系删除成功！",
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(externalActivity.this, "关系删除失败！",
							Toast.LENGTH_SHORT).show();
				}
			}
			if (action.equals("AlterShip")) {
				String reslut = (String) intent.getStringExtra("result");
				if (reslut.equals("succeed")) {
					list.get(postion).set_Name(Updata_relation);
					Toast.makeText(externalActivity.this, "关系修改成功！",
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(externalActivity.this, "关系修改失败！",
							Toast.LENGTH_SHORT).show();
				}
			}
			test.notifyDataSetChanged();
		}
	}

	@Override
	public int getLayout() {
		// TODO Auto-generated method stub
		return R.layout.external;

	}

	void initview() {
		btnSave = (Button) findViewById(R.id.btnSave);
		btnNew = (Button) findViewById(R.id.btnNew);
		btnqueding = (Button) findViewById(R.id.btnqueding);
		gr = (ListView) findViewById(R.id.test);
	}

	void initclick() {
		btnSave.setOnClickListener(this);
		btnqueding.setOnClickListener(this);
		btnNew.setOnClickListener(this);
	}

	@Override
	public void OnActCreate(Bundle savedInstanceState) {
		Intent intent = getIntent();
		String action = intent.getStringExtra("action");
		id = intent.getStringExtra("id");
		String name = intent.getStringExtra("name");
		String nnn = intent.getStringExtra("relation");
		if (nnn != null) {
			relation = nnn;
		}
		setTtile(name);
		setLeftImageBack();
		Log.i("libs", "action:" + action);
		Log.i("libs", "id:" + id);
		Log.i("libs", "name:" + name);
		if (id != null) {
			parentID = id;
			RelationshipBLL.SelectShip(mContext, id);
			type = action;
		} else {
			switch (action) {
			case "dy":
				RelationshipBLL.SelectShip(mContext, "2");
				type = action;
				relation += "地域";
				break;
			case "gk":
				RelationshipBLL.SelectShip(mContext, "1");
				type = action;
				relation += "关系归口";
				break;
			default:
				break;
			}
		}
		ReceiveBroadCast receiveBroadCast = new ReceiveBroadCast();
		IntentFilter filter = new IntentFilter();
		filter.addAction("lbs_SelectContactNumBydy");
		filter.addAction("lbs_SelectContactNumBygk");
		filter.addAction("SelectShip");
		filter.addAction("AddShip");
		filter.addAction("DeleteShip");
		registerReceiver(receiveBroadCast, filter);
		initview();
		initclick();
		test = new CommonAdapter<Relationship>(externalActivity.this, list,
				R.layout.externalone) {
			@Override
			public void convert(final ViewHolder holder, Relationship t) {
				CheckBox = (android.widget.CheckBox) holder
						.getView(R.id.checkbox);
				holder.setText(R.id.name, t.get_Name());
				holder.setText(R.id.num, t.get_Depict());
				CheckBox = (android.widget.CheckBox) holder.getView(R.id.checkbox);
				CheckBox.setChecked(t.isCheck);
				//复选框点击事件
				CheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					
					@Override
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						// TODO Auto-generated method stub
						 if (isChecked) {  
							 //Toast.makeText(mContext,"ss"+ list.get(holder.getPosition()).get_Name(), Toast.LENGTH_SHORT).show();
			                    state.put(holder.getPosition(), isChecked);  
			                    Log.i("mt", holder.getPosition()+"add:"+isChecked);
			                    list.get(holder.getPosition()).isCheck=isChecked;

			                } else {  
			                    state.put(holder.getPosition(), isChecked); 
			                    list.get(holder.getPosition()).isCheck=isChecked;
			                    Log.i("mt", holder.getPosition()+"remove:"+isChecked);
			                   
			                }  

				     
						 //Toast.makeText(mContext,"rr"+ state.get(position).getTel(), Toast.LENGTH_SHORT).show();
					}
				});
				if (editMode) {
					CheckBox.setVisibility(View.GONE);
					btnSave.setVisibility(View.VISIBLE);// 群发
					btnNew.setVisibility(View.VISIBLE);
					btnqueding.setVisibility(View.GONE);

				} else {
					CheckBox.setVisibility(View.VISIBLE);
					btnSave.setVisibility(View.GONE);
					btnNew.setVisibility(View.GONE);
					btnqueding.setVisibility(View.VISIBLE);
				}
			}
		};
		gr.setAdapter(test);
		gr.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				setTtile(list.get(arg2).get_Name());
				RelationshipBLL.SelectShip(mContext, list.get(arg2)
						.get_RelationshipID());
				relation += "-" + list.get(arg2).get_Name();
				if (islast == false) {
					parentID = list.get(arg2).get_RelationshipID();
				}
			}
		});
		gr.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				postion = arg2;
				gr.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
					@Override
					public void onCreateContextMenu(ContextMenu arg0,
							View arg1, ContextMenuInfo arg2) {
						MenuInflater inflator = new MenuInflater(
								externalActivity.this);
						inflator.inflate(R.menu.relation_menu, arg0);
					}
				});
				return false;
			}
		});
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.del:
			RelationshipBLL.DeleteShip(mContext, parentID);
			break;
		case R.id.updata:
			LayoutInflater factory1 = LayoutInflater
					.from(externalActivity.this);
			// 获取对话框中的EditText控件中的值
			final View textEntryView1 = factory1.inflate(
					R.layout.activityh_relation, null);
			final EditText etrelation = (EditText) textEntryView1
					.findViewById(R.id.etrelation);
			etrelation.setText(list.get(postion).get_Name());
			AlertDialog.Builder add1 = new AlertDialog.Builder(
					externalActivity.this);
			add1.setTitle("修改关系");
			add1.setView(textEntryView1);
			add1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int i) {
					String relation = etrelation.getText().toString();
					Updata_relation = relation;
					Relationship relationship = new Relationship();
					relationship.set_Name(relation);
					relationship.set_ParentID(parentID);
					RelationshipBLL.AlterShip(mContext, relationship);
				}
			});
			add1.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int i) {
				}
			});
			add1.show();// 显示对话框
			break;
		default:
			break;
		}
		return true;
	}

	public void OnViewClick(View v) {

		switch (v.getId()) {
		// 短信群发
		case R.id.btnSave:
			editMode = false;
			test.notifyDataSetChanged();
			setLeftImageHide();
			setLeftText("取消", new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub

					setLeftHide();
					setRightHide();
					setLeftImageBack();
					editMode = true;
					test.notifyDataSetChanged();
				}
			});
			OnClickListener listener = new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Toast.makeText(mContext, "全选", Toast.LENGTH_SHORT).show();
					//list.clear();
					for (int i = 0; i < list.size(); i++) {
						state.put(i, true);
						list.get(i).isCheck = true;

					}
					test.notifyDataSetChanged();

				}
			};
			setRightText("全选", listener);
			break;
		// 新建联系人
		case R.id.btnNew:
			LayoutInflater factory1 = LayoutInflater
					.from(externalActivity.this);
			// 获取对话框中的EditText控件中的值
			final View textEntryView1 = factory1.inflate(
					R.layout.activityh_relation, null);
			final EditText etrelation = (EditText) textEntryView1
					.findViewById(R.id.etrelation);
			AlertDialog.Builder add1 = new AlertDialog.Builder(
					externalActivity.this, R.style.my_dialog);
			add1.setTitle("添加关系");
			add1.setView(textEntryView1);
			add1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int i) {
					String relation = etrelation.getText().toString();
					Relationship relationship = new Relationship();
					relationship.set_Name(relation);
					relationship.set_ParentID(parentID);
					RelationshipBLL.AddShip(mContext, relationship);
				}
			});
			add1.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int i) {
				}
			});
			AlertDialog dialogsAlertDialog = add1.create();
			dialogsAlertDialog.show();// 显示对话框
			this.dialogTitleLineColor(dialogsAlertDialog, R.color.color_theme);
			break;
		case R.id.btnqueding:
			//确定
			setSelectList();
			for(int i=0;i<list.size();i++){
				if(state.get(i)!=null&&state.get(i)==true){
					SelectShipList.add(list.get(i).get_Name());
				}
			}
			if(SelectShipList.size()==0){
				Toast.makeText(externalActivity.this, "请至少选中一个！", Toast.LENGTH_SHORT).show();
				break;
			}
			else{
				showProgressDialog();
				if(type.equals("gk")){
					new Thread(new myThreadgk()).start();
				}
				if(type.equals("dy")){
					new Thread(new myThreaddy()).start();
				}
			}
			break;
		default:
			break;
		}

	}
	class myThreadgk implements Runnable {
		@Override
		public void run() {
			ContactInfoServise conSer=new ContactInfoServise(mContext);
			List<ContactInfoBySqlite> listcon=new ArrayList<ContactInfoBySqlite>();
			for(String gk:SelectShipList){
				List<ContactInfoBySqlite> list=conSer.SelectContactBygk(gk);
				listcon.addAll(list);
			}
			Message message = new Message();   
	        message.what = constantUtil.Num_SelectContactBygk;
	        message.obj=listcon;
	        myHandler.sendMessage(message);
		}
	}
	class myThreaddy implements Runnable {
		@Override
		public void run() {
			ContactInfoServise conSer=new ContactInfoServise(mContext);
			List<ContactInfoBySqlite> listcon=new ArrayList<ContactInfoBySqlite>();
			for(String dy:SelectShipList){
				List<ContactInfoBySqlite> list=conSer.SelectContactBydy(dy);
				listcon.addAll(list);
			}
			Message message = new Message();   
	        message.what = constantUtil.Num_SelectContactBydy;
	        message.obj=listcon;
	        myHandler.sendMessage(message);
		}
	}
	public static final void dialogTitleLineColor(Dialog dialog, int colors) {
		Context context = dialog.getContext();
		int divierId = context.getResources().getIdentifier(
				"android:id/titleDivider", null, null);
		View divider = dialog.findViewById(divierId);
		divider.setBackgroundColor(colors);
		divider.setBackgroundResource(R.drawable.show_head_toast_bg);
	}
	
	private void setSelectList() {
		if(SelectShipList.size()!=0){
			SelectShipList.clear();
		}
	}
}
